/**
 * Created by Administrator on 2016/5/17.
 */
const express = require('express');
const router = express.Router();

const urlEncoded = require('body-parser').urlencoded({extended: false});

// 使用redis存储数据
const redis = require('redis');
var client = redis.createClient();
// 通过选择不同的库实现生产库与测试库分离
client.select((process.env.NODE_ENV || 'development').length);

router.route('/')
    .get(function (req, res) {
        client.hkeys('cities', function (err, keys) {
            if (err) throw err;
            res.json(keys);
        });
    })
    .post(urlEncoded, function (req, res) {
        var newCity = req.body;
        if (!newCity.name || !newCity.desc) {
            res.sendStatus(400);
            return false;
        }
        client.hset('cities', newCity.name, newCity.desc);
        res.status(201).json(newCity.name);
    });

router.route('/:name')
    .delete(function (req, res) {
        client.hdel('cities', req.params.name);
        res.sendStatus(204);
    })
    .get(function (req, res) {
        var cityName = req.params.name;
        client.hget('cities', cityName, function (err, desc) {
            res.render('desc.ejs',
                {
                    city: {name: cityName, desc: desc}
                });
        });
    });

module.exports = router;